const { createHash, createToken } = require('../common')
const { teacher } = require('../models')

module.exports = {
    /**
     * 注册老师
     * @return 成功时返回新增的老师，失败时返回失败信息
     */
    async register(ctx, next) {
        try {
            let result = await teacher.create(ctx.request.body);
            return ctx.body = { status: 'ok', data: result };
        } catch (e) {
            return ctx.body = { status: 'fail', data: e.message };
        }
    },
    /**
     * 登录老师
     * @return 成功时返回token和登录老师信息，失败则返回错误信息
     */
    async login(ctx, next) {
        try {
            let result = await teacher.findOne({ code: ctx.request.body.code }).exec();
            let userInfo = { _id: result._id, code: result.code, name: result.name, identify: result.identify }
            if (createHash(ctx.request.body.pwd) == result.pwd) {
                let token = createToken(userInfo);
                return ctx.body = { status: 'ok', data: { token: token, user: userInfo } }
            } else {
                return ctx.body = { status: 'fail', data: '检查密码' }
            }
        } catch (e) {
            return ctx.body = { status: 'fail', data: e.message }
        }
    },
    /**
     * 根据id获取获取指定的老师
     * @return 成功时返回老师信息，否则返回错误信息
     */
    async getTeacher(ctx, next) {
        try {
            let result = await teacher.findById(ctx.params.id).select({pwd : 0}).exec();
            return ctx.body = { status: 'ok', data: result }
        } catch (error) {
            return ctx.body = { status: 'fail', data: e.message }
        }
    },

}